package com.orifine.web;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

public class MemoryInternationalization implements Internationalization {
	private Map<String, Properties> message = new HashMap<String, Properties>();
	
	public MemoryInternationalization add(String key, String message){
		load().put(key, message);
		return this;
	}
	
	public MemoryInternationalization add(Locale locale, String key, String message){
		add(locale.toString().toLowerCase(), key, message);
		return this;
	}
	
	public MemoryInternationalization add(String localeName, String key, String message){
		Properties properties = this.message.get(localeName);
		if(properties == null){
			properties = new Properties();
			this.message.put(localeName, properties);
		}
		properties.put(key, message);
		return this;
	}
	
	/**
	 * @see ResourceInternationalization#getMessage(String, String)
	 */
	public String getMessage(Locale locale, String messageName){
		Properties properties = load(locale);
		return properties.getProperty(messageName);
	}
	
	public String getMessage(String messageName){
		return load().getProperty(messageName);
	}

	/**
	 * 加载资源文件
	 * @param localeName 加载的语言
	 * @return 返回资源对象
	 */
	private Properties load(Locale locale){
		String localeName = locale.toString().toLowerCase();
		if(message.containsKey(localeName)){
			return message.get(localeName);
		} else {
			return load();
		}
	}
	
	/**
	 * 加载资源文件
	 * @return 返回资源对象
	 */
	private Properties load(){
		if(!message.containsKey("default")){
			message.put("default", new Properties());
		}
		return message.get("default");
	}
}
